<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="上架状态" prop="spuStatus">
        <el-select
          v-model="queryParams.spuStatus"
          placeholder="请选择状态"
          clearable
          class="!w-240px"
        >
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openPlatformCourse"
          v-hasPermi="['train:course:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 上架平台课程
        </el-button>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['train:course:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新建课程
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      ref="multipleTableRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="课程封面" align="center" prop="courseCoverUrl">
        <template #default="scope">
          <div class="w-full flex justify-center items-center">
            <el-image
              class="w-20 h-20"
              :src="getOSSURL(scope.row.courseCoverUrl)"
              :preview-src-list="[getOSSURL(scope.row.courseCoverUrl)]"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName" />
      <el-table-column label="车型" align="center" prop="carType" />
      <el-table-column label="课程有效天数" align="center" prop="validDays" />
      <el-table-column label="上架状态" align="center" prop="spuStatus">
        <template #default="scope">
          <el-tag class="ml-2" :type="statusFormatter(scope.row.spuStatus).type">{{
            statusFormatter(scope.row.spuStatus).text
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
      />
      <el-table-column label="操作" align="center" fixed="right" width="230">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['train:course:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            @click="catalogDetail(scope.row.id)"
            v-hasPermi="['train:course:query']"
          >
            目录
          </el-button>
          <el-button
            link
            type="primary"
            @click="openCheckoutConfigForm(scope.row.skuId)"
            v-hasPermi="['train:course:update']"
          >
            分润配置
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['train:course:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <!-- <CreateCourseForm ref="formRef" @success="getList" /> -->
  <!-- 添加目录弹窗：添加/修改 -->
  <CatalogDetailForm ref="catalogDetailFormRef" @success="getList" />
  <!-- 上架平台课程弹窗 -->
  <PlatformCourseForm ref="platformCourseFormRef" />
  <!-- 分润配置弹窗 -->
  <CheckoutConfigForm ref="checkoutConfigFormRef" />
  <!-- 编辑课程弹窗 -->
  <EditCourseForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts" name="Service">
import { dateFormatter } from '@/utils/formatTime'
import * as CourseApi from '@/api/course/index'
import * as PlatformCourseApi from '@/api/course/platform-course'
import CatalogDetailForm from './form/catalog-detail-form.vue'
import PlatformCourseForm from './form/platform-course-form.vue'
import CheckoutConfigForm from '@/views/client-mall/product/sku/checkout-config-form.vue'
import EditCourseForm from './form/edit-course-form.vue'
import { statusDict } from './common'
import { getOSSURL } from '@/utils/oss'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<CourseApi.CourseVO[]>([]) // 列表的数据
const queryParams = reactive<PageParam & CourseApi.CourseQueryDTO>({
  pageNo: 1,
  pageSize: 10,
  courseName: undefined,
  spuStatus: undefined
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CourseApi.getPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  // queryFormRef.value.resetFields()
  // handleQuery()

  // PlatformCourseApi.bind(['1719994432352141313']).then((res) => {
  //   console.log('绑定结束：', res)
  // })

  PlatformCourseApi.unbind(['1719994432352141313']).then((res) => {
    console.log('解绑结束：', res)
  })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格查看目录详情 */
const catalogDetailFormRef = ref()
const catalogDetail = (id: string) => {
  router.push({ path: '/course/course-catalog', query: { courseId: id } })
}

/** 上架平台课程弹窗 */
const platformCourseFormRef = ref()
const openPlatformCourse = () => {
  platformCourseFormRef.value.open()
}

/** 分润配置 */
const checkoutConfigFormRef = ref()
const openCheckoutConfigForm = (id: string) => {
  checkoutConfigFormRef.value.open(id)
}

/** 处理表格多选 */
const multipleTableRef = ref(null)
const multipleSelection = ref<CourseList[]>([])
const handleSelectionChange = (val: CourseList[]) => {
  multipleSelection.value = val
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CourseApi.deleteById(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 表格项状态格式化  1 启用 2 禁用*/
const statusFormatter = (val: CourseApi.CourseStatus) => {
  const status = statusDict.find((item) => item.value === val)
  return {
    type: status?.type,
    text: status?.label
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
